﻿using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using B.S.Medical.Api.Read.Application.Command.Department;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.ErrorCode;
using MediatR;
using OfficeOpenXml;
using B.S.Medical.Domain.Department;
using B.S.Medical.Infrastructure.Interface;
using System.Linq;


namespace B.S.Medical.Api.Read.Application.Handler.Department
{
    public class DaoChuCommandHandle : IRequestHandler<DaoChuCommand, ApiResult<List<DepartmentDaoChuDto>>>
    {
        private readonly IBaseRepository<ManageModel> _manageRepository;
        public DaoChuCommandHandle(IBaseRepository<ManageModel> manageRepository)
        {
            _manageRepository = manageRepository;
        }

        public async Task<ApiResult<List<DepartmentDaoChuDto>>> Handle(DaoChuCommand request, CancellationToken cancellationToken)
        {
            // Fetch data logic here
            List<DepartmentDaoChuDto> data = FetchData(request.DepartmentName);

            // Export to Excel
            var excelFile = ExportToExcel(data);

            // Return the result
            return new ApiResult<List<DepartmentDaoChuDto>>
            {
                Data = data,
                Success = true,
                Message = "Data exported successfully",
                File = excelFile
            };
        }

        private List<DepartmentDaoChuDto> FetchData(string? departmentName)
        {
            var query = _manageRepository.GetAll().Where(x => !x.IsDeleted);
            if (!string.IsNullOrEmpty(departmentName))
            {
                query = query.Where(x => x.DepartmentName.Contains(departmentName));
            }
            return query.Select(x => new DepartmentDaoChuDto
            {
                Id = x.Id,
                DepartmentName = x.DepartmentName,
                CampusId = x.CampusId,
                ParetId = x.ParetId,
                DepartmentAddr = x.DepartmentAddr,
                Status = x.Status
            }).ToList();
        }

        private byte[] ExportToExcel(List<DepartmentDaoChuDto> data)
        {
            // 设置EPPlus的LicenseContext，避免license异常
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add("Departments");
                worksheet.Cells[1, 1].Value = "Id";
                worksheet.Cells[1, 2].Value = "Department Name";
                worksheet.Cells[1, 3].Value = "Campus Id";
                worksheet.Cells[1, 4].Value = "Parent Id";
                worksheet.Cells[1, 5].Value = "Department Address";
                worksheet.Cells[1, 6].Value = "Status";

                for (int i = 0; i < data.Count; i++)
                {
                    worksheet.Cells[i + 2, 1].Value = data[i].Id;
                    worksheet.Cells[i + 2, 2].Value = data[i].DepartmentName;
                    worksheet.Cells[i + 2, 3].Value = data[i].CampusId;
                    worksheet.Cells[i + 2, 4].Value = data[i].ParetId;
                    worksheet.Cells[i + 2, 5].Value = data[i].DepartmentAddr;
                    worksheet.Cells[i + 2, 6].Value = data[i].Status;
                }

                return package.GetAsByteArray();
            }
        }
    }
}
